// pages/gjIndex/orderDetail/paymentItems.js
import config from '../../../config.js';
const base = config;
var util = require('../../../utils/util.js');
//qqmap-wx-jssdk.min.js
// 引入SDK核心类
var QQMapWX = require('../../components/qqmap-wx-jssdk.min.js');

// 实例化API核心类
var map = new QQMapWX({
  key: 'D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW' // 必填
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    polyline: [],
    orderId: null,
    typeId: null,
    payItems: [],
    order: null,
    type: 0,
    speed: null,
    accuracy: 6,
    key: "D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW",
    isShowMap: false,
    paths: {},
    pickPath: null,
    sendPath: null,
    resultPick: null,
    resultSend: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var orderId = options.orderId;
    var typeId = options.typeId;
    var type = options.type;
    var isShowMap = false;

    if (type != null) {
      this.setData({
        type: type
      })
    }

    if (typeId == 4 || typeId == 5) {
      isShowMap = true;
    }

    this.setData({
      orderId: orderId,
      typeId: typeId,
      isShowMap: isShowMap
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.loadOrderData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  submitAction: function () {
    var that = this;
    var items = JSON.stringify(this.data.payItems);
    wx.showModal({
      title: "温馨提示",
      content: "是否确认将报价推送给用户？",
      showCancel: true,
      confirmColor: "#137AF0",
      success: function (er) {
        if (er.confirm) {
          wx.showLoading({
            title: '正在操作',
          })
          wx.request({
            url: base.generatePriceList,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': wx.getStorageSync("session")
            },
            data: {
              orderId: that.data.orderId,
              items: items,
              type: that.data.type
            },
            success: function (res) {
              wx.hideLoading();
              if (res.data.status == 200) {
                wx.showToast({
                  title: '成功完成订单',
                })
                if (that.data.type != 0) {
                  wx.setStorageSync("isGoOn", false);
                } else {
                  wx.setStorageSync("isGoOn", true);
                }
                wx.navigateBack({
                  delta: 1
                })
              } else {
                wx.showToast({
                  title: "状态设置失败",
                  icon: "none"
                })
              }
            }
          })
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  loadOrderData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: that.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          that.setData({
            order: res.data.data
          })

          that.loadData();

        } else {
          wx.showToast({
            title: '订单信息获取失败',
            icon: 'none',
            duration: 1500
          })
          return false;
        }
      }

    })
  },
  loadData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getPayItemList,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        typeId: this.data.typeId,
        orderId: that.data.orderId,
        type: that.data.type
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            for (var i = 0; i < res.data.data.length; i++) {
              var item = res.data.data[i];
              //item['unit'] = 1;
              res.data.data[i] = item;
            }
            that.setData({
              payItems: res.data.data,
            })

            if (that.data.isShowMap) {
              // that.locatedAction();
              that.loadPoylineData();
            }

          }

        }
      }

    })
  },
  loadPoylineData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getPoyline,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        orderId: that.data.orderId,
        index: 4
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            that.setData({
              paths: res.data.data
            })

            var points = [];
            var paths = res.data.data;
            if (paths != null && paths.length > 0) {
              //将解压后的坐标放入点串数组pl中
              var pl = [];
              for (var i = 0; i < paths.length; i++) {
                var item = paths[i];
                if (item.carSenType.typeId == 1) {
                  that.setData({
                    "pickPath.start": item,
                    latitude: item.lat,
                    longitude: item.lng,
                  })
                } else if (item.carSenType.typeId == 2) {
                  that.setData({
                    "pickPath.end": item
                  })
                } else if (item.carSenType.typeId == 3) {
                  that.setData({
                    "sendPath.start": item,
                    latitude: item.lat,
                    longitude: item.lng,
                  })
                } else if (item.carSenType.typeId == 4) {
                  that.setData({
                    "sendPath.end": item
                  })
                }
              }

            }


            that.setData({
              isShowMap: true,
            })


            that.calculateDinstance(that.data.pickPath, 1);
            that.calculateDinstance(that.data.sendPath, 2);
            that.driving(that.data.pickPath, '#FF0000DD');
            that.driving(that.data.sendPath, '#137AF0');

          }

        } 
      }

    })
  },

  engineNumberInput: function(e) {
    var item = e.currentTarget.dataset.item;
    var value = e.detail.value;
    item.price = value;
    this.setPayItem(item);
  },
  engineUnitInput: function(e) {
    var item = e.currentTarget.dataset.item;
    var value = e.detail.value;
    item['unit'] = value;
    this.setPayItem(item);
  },
  setPayItem: function(item) {
    var data = this.data.payItems;
    for (var i = 0; i < data.length; i++) {
      var it = data[i];
      if (it.itemId == item.itemId) {
        data[i] = item
      }
    }

    this.setData({
      payItems: data
    })
  },
  planningAction: function() {
    wx.navigateTo({
      url: '../map/planningMap',
    })
  },
  //事件回调函数
  driving: function(point, color) {
    var _this = this;
    if (point != null && point.start != null) {
      console.log(point);

      var from = "" + point.start.lat + "," + point.start.lng;
      var to = "" + point.end.lat + "," + point.end.lng;
      var key = _this.data.key;
      var url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + from + '&to=' + to + '&key=' + key;
      console.log(url);
      //网络请求设置
      var opt = {
        //WebService请求地址，from为起点坐标，to为终点坐标，开发key为必填
        url: url,
        method: 'GET',
        dataType: 'json',
        //请求成功回调
        success: function(res) {
          console.log(res);

          var ret = res.data
          if (ret.status != 0) return; //服务异常处理
          var coors = ret.result.routes[0].polyline,
            pl = [];
          //坐标解压（返回的点串坐标，通过前向差分进行压缩）
          var kr = 1000000;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
          }
          //将解压后的坐标放入点串数组pl中
          for (var i = 0; i < coors.length; i += 2) {
            pl.push({
              latitude: coors[i],
              longitude: coors[i + 1]
            })
          }
          //设置polyline属性，将路线显示出来
          var polyline = _this.data.polyline;
          polyline.push({
            points: pl,
            color: color,
            width: 4
          });

          _this.setData({
            isShowMap: true,
            polyline: polyline
          })
        }
      };
      wx.request(opt);
    }
  },
  calculateDinstance: function(path, type) {
    var that = this;
    if (path != null && path.start != null) {
      // 调用接口
      map.calculateDistance({
        mode: 'driving',
        from: {
          latitude: path.start.lat,
          longitude: path.start.lng
        },
        to: [{
          latitude: path.end.lat,
          longitude: path.end.lng
        }],
        success: function(res) {
          console.log(res);
          that.setResultData(res.result.elements, type);


        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      });
    }

  },
  setResultData: function(res, type) {
    var that = this;
    if (res != null && res.length > 0) {
      var item = res[0];
      var result = {};
      result['distance'] = item.distance;
      result['duration'] = util.formatSeconds(item.duration);
      if (type == 1) {
        that.setData({
          resultPick: result
        })

      } else {
        that.setData({
          resultSend: result
        })
      }

      //计算公里数
      var dinstance = item.distance / 1000;
      var data = that.data.payItems;
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.limit > 0) {
          console.log(dinstance);
          console.log(item.unit);
          if (dinstance > item.limit) {
            var count = (dinstance - item.limit) / item.unit;
            item.unit = Math.round(count);
            data[i] = item;
          } else {
            item.unit = 0;
            data[i] = item;
          }
        }
      }

      that.setData({
        payItems: data
      })
    }


  }

})